<template>
  <div class="landlord-houses-container">
    <!-- 固定顶部标题和搜索栏 -->
    <div class="fixed-header">
      <div class="page-header">
        <h2 class="title">我的房源管理</h2>
        <!-- 新增按钮容器，使用绝对定位靠右 -->
        <div class="button-container">
          <el-button type="primary" @click="handleCreateHouse">新增房源</el-button>
        </div>
      </div>
      <div class="search-container">
        <el-input
            v-model="searchQuery"
            placeholder="搜索房源标题/ID"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
            class="search-bar"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 可滚动的内容区域 -->
    <div class="scrollable-content">
      <!-- 主要内容区域 -->
      <div class="content-area">
        <!-- 有房源时显示表格 -->
        <el-table
            v-if="houses.length > 0 && !loading"
            :data="filteredHouses"
            stripe
            border
            style="width: 100%"
            @row-click="handleRowClick"
            :height="tableHeight"
            max-height="600px"
            :header-cell-style="{ background: '#f0f4f8', color: '#333' }"
        >
          <el-table-column prop="houseid" label="房源ID" width="120" fixed="left">
            <template #header>
              <div class="table-header-cell">房源ID</div>
            </template>
          </el-table-column>

          <el-table-column label="房源图片" width="150" fixed="left">
            <template #default="scope">
              <div class="image-container">
                <el-image
                    style="width: 120px; height: 80px"
                    :src="getCoverImage(scope.row.images)"
                    fit="contain"
                    :preview-src-list="getAllImages(scope.row.images)"
                    hide-on-click-modal
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><picture /></el-icon>
                      <span>暂无图片</span>
                    </div>
                  </template>
                </el-image>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="title" label="房源标题" min-width="200">
            <template #header>
              <div class="table-header-cell">房源标题</div>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="房源状态" width="150">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ getStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button-group>
                <el-button
                    type="primary"
                    size="small"
                    :round="true"
                    @click.stop="handleViewDetails(scope.row)"
                >
                  详情
                </el-button>
                <el-button
                    type="danger"
                    size="small"
                    :round="true"
                    @click.stop="handleDelete(scope.row.houseid)"
                >
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-icon class="loading-icon"><loading /></el-icon>
          <span>加载中...</span>
        </div>

        <!-- 无房源时的提示 -->
        <div v-if="!loading && houses.length === 0" class="empty-container">
          <el-empty description="暂无房源数据">
            <el-button type="primary" @click="handleCreateHouse">立即添加房源</el-button>
          </el-empty>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Picture, Loading } from '@element-plus/icons-vue'
import axios from 'axios'
import common_util from '../../util/common_util.js'
import { useRouter } from 'vue-router'

const router = useRouter()
const searchQuery = ref('')
const statusFilter = ref('')
const houses = ref([])
const loading = ref(false)

// 状态选项与映射
const statusMap = {
  pending: { label: '待审核', type: 'warning' },
  published: { label: '已发布', type: 'success' },
  rejected: { label: '已拒绝', type: 'danger' },
  rented: { label: '已出租', type: 'info' },
  hidden: { label: '已隐藏', type: '' }
}

// 计算属性
const filteredHouses = computed(() => {
  if (!searchQuery.value) return houses.value
  const query = searchQuery.value.toLowerCase()
  return houses.value.filter(house =>
      house.title.toLowerCase().includes(query) ||
      String(house.houseid).includes(query)
  )
})

// 动态计算表格高度
const tableHeight = ref(400) // 默认高度

onMounted(() => {
  fetchHouses()
  updateTableHeight()

  // 监听窗口大小变化，更新表格高度
  window.addEventListener('resize', updateTableHeight)
})

// 移除组件时取消事件监听
const onUnmounted = () => {
  window.removeEventListener('resize', updateTableHeight)
}

// 更新表格高度函数
const updateTableHeight = () => {
  nextTick(() => {
    const headerHeight = document.querySelector('.fixed-header').offsetHeight
    const windowHeight = window.innerHeight

    // 计算表格可用高度（减去顶部固定区域和一些边距）
    const tableHeightValue = windowHeight - headerHeight - 80 // 80为其他间距

    // 设置最小高度限制
    tableHeight.value = Math.max(tableHeightValue, 300)
  })
}

// 获取房源列表
const fetchHouses = async () => {
  loading.value = true
  try {
    const params = {
      keyword: searchQuery.value.trim(),
      status: statusFilter.value
    }

    const response = await axios.get('/api/houses/user', {
      params,
      headers: common_util.accessHeader()
    })

    if (response.data.code === 0) {
      const housesByStatus = response.data.data
      houses.value = []

      // 处理不同状态的房源
      for (const [status, houseList] of Object.entries(housesByStatus)) {
        houseList.forEach(house => {
          // 规范化图片数据
          const images = house.images?.gallery || []
          if (house.images?.cover?.image_url) {
            images.unshift({
              ...house.images.cover,
              is_cover: true
            })
          }

          houses.value.push({
            ...house,
            status: status,
            images: images,
            fullAddress: formatAddress(house.address)
          })
        })
      }
    } else {
      handleApiError(response.data)
    }
  } catch (error) {
    handleNetworkError(error)
  } finally {
    loading.value = false
  }
}

// 图片处理
const getCoverImage = (images) => {
  const cover = images?.find(img => img.is_cover)
  return cover?.image_url || images?.[0]?.image_url || ''
}

const getAllImages = (images) => {
  return images?.map(img => img.image_url) || []
}

// 状态显示
const getStatusLabel = (status) => {
  return statusMap[status]?.label || status
}

const getStatusTagType = (status) => {
  return statusMap[status]?.type || ''
}

// 地址格式化
const formatAddress = (address) => {
  if (!address) return ''
  return `${address.province || ''}${address.city || ''}${address.district || ''}${address.street || ''}`
}

// 错误处理
const handleApiError = (errorData) => {
  const errorMsg = errorData.extra_msg || errorData.msg || '请求失败'
  ElMessage.error(errorMsg)

  if (errorData.code === 401) {
    router.push('/login')
  }
}

const handleNetworkError = (error) => {
  if (error.response) {
    ElMessage.error(`服务器错误: ${error.response.status}`)
    if (error.response.status === 401) {
      router.push('/login')
    }
  } else if (error.request) {
    ElMessage.error('请求超时，请检查网络连接')
  } else {
    ElMessage.error(`请求错误: ${error.message}`)
  }
}

// 操作处理
const handleSearch = () => {
  fetchHouses()
}

const handleRowClick = (row) => {
  // 可选：点击行也可以跳转详情
  // handleViewDetails(row)
}

const handleViewDetails = (house) => {
  router.push({
    name: 'HouseDetail',
    params: { houseId: Number(house.houseid) }
  })
}

const handleEditHouse = (houseId) => {
  router.push({ name: 'EditHouse', params: { houseId } })
}

const handleDelete = async (houseId) => {
  try {
    await ElMessageBox.confirm('确定删除该房源吗？删除后不可恢复', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await axios.delete(`/api/houses/${houseId}`, {
      headers: common_util.accessHeader()
    })

    if (response.data.code === 0) {
      ElMessage.success('删除成功')
      fetchHouses()
    } else {
      handleApiError(response.data)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleCreateHouse = () => {
  router.push({ name: 'AddHouses' })
}
</script>

<style scoped>
.landlord-houses-container {
  position: relative;
  min-height: 100vh;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.fixed-header {
  position: sticky;
  top: 0;
  background: white;
  z-index: 10;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  padding: 10px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
}

.button-container {
  display: flex;
  align-items: center;
}

.search-container {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
}

.search-bar {
  width: 300px;
  border-radius: 4px;
}

.scrollable-content {
  height: calc(100vh - 150px);
  overflow-y: auto;
  padding: 10px 0;
}

.content-area {
  width: 100%;
}

.table-container {
  width: 100%;
  margin-top: 10px;
}

.el-table {
  margin: 0;
  border-radius: 8px;
  overflow: hidden;
}

.table-header-cell {
  font-weight: 500;
  color: #333;
}

.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 滚动条样式 */
.scrollable-content::-webkit-scrollbar {
  width: 6px;
}

.scrollable-content::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 4px;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .landlord-houses-container {
    padding: 15px;
  }

  .search-bar {
    width: 250px;
  }
}

@media (max-width: 768px) {
  .fixed-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .search-container {
    justify-content: flex-start;
    width: 100%;
  }

  .scrollable-content {
    height: calc(100vh - 200px);
  }
}

/* 加载动画 */
.loading-icon {
  font-size: 40px;
  margin-bottom: 10px;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 图片错误状态 */
.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  font-size: 12px;
}

.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

/* 按钮组 */
.el-button-group {
  display: flex;
  gap: 5px;
}
</style>